package com.mqtt.handler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mqtt.handler.ProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import com.mqtt.model.MqttMessage;
import com.mqtt.service.converter.ProtocolConverter;

/**
 * 设备消息处理器
 */
@Slf4j
@Component
public class DeviceMessageHandler {

    @Autowired
    private ProtocolHandler protocolHandler;

    @Autowired
    private ProtocolConverter protocolConverter;

    /**
     * 处理数据消息
     */
    public void handleDataMessage(MqttMessage mqttMessage) {
        try {
            log.debug("Handling data message from device: {}", mqttMessage.getDeviceId());

            // 协议转换
            Map<String, Object> convertedData = protocolConverter.convert(mqttMessage.getPayload());

            // 数据验证
            if (!validateData(convertedData)) {
                log.warn("Invalid data from device: {}", mqttMessage.getDeviceId());
                return;
            }

            // 数据处理
            processData(mqttMessage.getDeviceId(), convertedData);

        } catch (Exception e) {
            log.error("Error handling data message from device: {}", mqttMessage.getDeviceId(), e);
        }
    }

    /**
     * 处理状态消息
     */
    public void handleStatusMessage(MqttMessage mqttMessage) {
        try {
            log.debug("Handling status message from device: {}", mqttMessage.getDeviceId());

            JSONObject status = JSON.parseObject(mqttMessage.getPayload());

            // 处理在线/离线状态
            String statusValue = status.getString("status");
            if ("online".equals(statusValue)) {
                handleDeviceOnline(mqttMessage.getDeviceId(), status);
            } else if ("offline".equals(statusValue)) {
                handleDeviceOffline(mqttMessage.getDeviceId(), status);
            }

            // 处理其他状态信息
            processStatusInfo(mqttMessage.getDeviceId(), status);

        } catch (Exception e) {
            log.error("Error handling status message from device: {}", mqttMessage.getDeviceId(), e);
        }
    }

    /**
     * 处理命令响应
     */
    public void handleCommandResponse(MqttMessage mqttMessage) {
        try {
            log.debug("Handling command response from device: {}", mqttMessage.getDeviceId());

            JSONObject response = JSON.parseObject(mqttMessage.getPayload());

            String commandId = response.getString("commandId");
            String result = response.getString("result");

            // 更新命令执行结果
            updateCommandResult(commandId, result);

            // 触发回调
            triggerCommandCallback(mqttMessage.getDeviceId(), commandId, response);

        } catch (Exception e) {
            log.error("Error handling command response from device: {}", mqttMessage.getDeviceId(), e);
        }
    }

    /**
     * 处理告警消息
     */
    public void handleAlarmMessage(MqttMessage mqttMessage) {
        try {
            log.warn("Handling alarm message from device: {}", mqttMessage.getDeviceId());

            JSONObject alarm = JSON.parseObject(mqttMessage.getPayload());

            String alarmType = alarm.getString("type");
            String level = alarm.getString("level");
            String description = alarm.getString("description");

            // 记录告警
            logAlarm(mqttMessage.getDeviceId(), alarmType, level, description);

            // 触发告警处理流程
            if ("critical".equals(level) || "high".equals(level)) {
                triggerAlarmNotification(mqttMessage.getDeviceId(), alarm);
            }

        } catch (Exception e) {
            log.error("Error handling alarm message from device: {}", mqttMessage.getDeviceId(), e);
        }
    }

    /**
     * 处理注册消息
     */
    public void handleRegisterMessage(MqttMessage mqttMessage) {
        try {
            log.info("Handling register message from device: {}", mqttMessage.getDeviceId());

            JSONObject registerInfo = JSON.parseObject(mqttMessage.getPayload());

            // 验证注册信息
            if (!validateRegisterInfo(registerInfo)) {
                log.warn("Invalid register info from device: {}", mqttMessage.getDeviceId());
                return;
            }

            // 处理设备注册
            processDeviceRegister(mqttMessage.getDeviceId(), registerInfo);

            // 发送注册响应
            sendRegisterResponse(mqttMessage.getDeviceId(), true, "Registration successful");

        } catch (Exception e) {
            log.error("Error handling register message from device: {}", mqttMessage.getDeviceId(), e);
            sendRegisterResponse(mqttMessage.getDeviceId(), false, "Registration failed: " + e.getMessage());
        }
    }

    /**
     * 验证数据
     */
    private boolean validateData(Map<String, Object> data) {
        // 实现数据验证逻辑
        if (data == null || data.isEmpty()) {
            return false;
        }

        // 检查必要字段
        return data.containsKey("timestamp") && data.containsKey("data");
    }

    /**
     * 处理数据
     */
    private void processData(String deviceId, Map<String, Object> data) {
        // 实现数据处理逻辑
        log.info("Processing data for device: {}, data: {}", deviceId, data);
    }

    /**
     * 处理设备上线
     */
    private void handleDeviceOnline(String deviceId, JSONObject status) {
        log.info("Device online: {}", deviceId);
        // 实现设备上线处理逻辑
    }

    /**
     * 处理设备离线
     */
    private void handleDeviceOffline(String deviceId, JSONObject status) {
        log.info("Device offline: {}", deviceId);
        // 实现设备离线处理逻辑
    }

    /**
     * 处理状态信息
     */
    private void processStatusInfo(String deviceId, JSONObject status) {
        // 实现状态信息处理逻辑
        log.debug("Processing status info for device: {}", deviceId);
    }

    /**
     * 更新命令结果
     */
    private void updateCommandResult(String commandId, String result) {
        // 实现命令结果更新逻辑
        log.info("Command {} result: {}", commandId, result);
    }

    /**
     * 触发命令回调
     */
    private void triggerCommandCallback(String deviceId, String commandId, JSONObject response) {
        // 实现命令回调逻辑
        log.debug("Triggering callback for command: {}", commandId);
    }

    /**
     * 记录告警
     */
    private void logAlarm(String deviceId, String type, String level, String description) {
        log.warn("Alarm from device {}: type={}, level={}, desc={}",
                deviceId, type, level, description);
    }

    /**
     * 触发告警通知
     */
    private void triggerAlarmNotification(String deviceId, JSONObject alarm) {
        // 实现告警通知逻辑
        log.info("Triggering alarm notification for device: {}", deviceId);
    }

    /**
     * 验证注册信息
     */
    private boolean validateRegisterInfo(JSONObject registerInfo) {
        // 实现注册信息验证逻辑
        return registerInfo.containsKey("deviceType") &&
                registerInfo.containsKey("version") &&
                registerInfo.containsKey("manufacturer");
    }

    /**
     * 处理设备注册
     */
    private void processDeviceRegister(String deviceId, JSONObject registerInfo) {
        // 实现设备注册处理逻辑
        log.info("Processing device registration: {}", deviceId);
    }

    /**
     * 发送注册响应
     */
    private void sendRegisterResponse(String deviceId, boolean success, String message) {
        // 构建响应消息
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());

        // 发送响应到设备
        String topic = "device/" + deviceId + "/register/response";
        protocolHandler.sendMessage(topic, JSON.toJSONString(response));
    }
}